package com.baitengsoft.patentservicemonitor.job.cloud.patent.hub.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;

import com.baitengsoft.patentservicemonitor.api.service.WebPlatformService;
import com.baitengsoft.patentservicemonitor.job.cloud.patent.hub.enums.PatentTypeEnum;
import com.baitengsoft.patentservicemonitor.job.cloud.patent.hub.service.CustomThreadPoolExecutor;
import com.baitengsoft.patentservicemonitor.job.cloud.patent.hub.service.FetchPatentService;
import com.baitengsoft.patentservicemonitor.job.entity.PatentHubDataEntity;
import com.baitengsoft.patentservicemonitor.job.model.PacPatentinfoModel;
import com.baitengsoft.patentservicemonitor.job.model.hub.*;
import com.baitengsoft.patentservicemonitor.job.redis.service.IRedisHashService;
import com.baitengsoft.patentservicemonitor.job.redis.service.IRedisListService;

import com.baitengsoft.patentservicemonitor.job.service.PatentHubDataService;
import com.baitengsoft.patentservicemonitor.job.utils.HttpUtils;
import com.baitengsoft.patentservicemonitor.job.utils.PatentHubTransferUtil;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangze
 * @date 2018-08-19 15:13.
 **/
@Service
public class PatentHubService implements FetchPatentService {
    private final static Logger LOGGER = LoggerFactory.getLogger(PatentHubService.class);

    private static final String TOKEN = "ff3249387992819db124af2332bf03c94b176e88";
    public static final String KEY = "ZHOUCHENG1";
    public static final String KEY_LIST = "ZHOUCHENGLIST1";
    public static final long PAGE_SIZE = 50L;

    private String areaName;


    @PostConstruct
    private void initAreaName() {
        areaName = webPlatformService.getAreaName(2);
    }


    @Autowired
    protected DataSource dataSource;
    @Autowired
    private IRedisHashService redisHashService;
    @Autowired
    private IRedisListService redisListService;
    @Autowired
    private WebPlatformService webPlatformService;
    @Autowired
    private PatentHubDataService patentHubDataService;

    @Override
    public void insertPatent(String address, int year) {

    }

    @Override
    public void insertPatent(String address) {

    }

    @Override
    public void insertPatentOut() {

    }

    /**
     * 从专利汇拉取数据到redis
     */
    @Transactional(rollbackFor = Exception.class)
    public void printData3(int year) {
        long beginTime = System.currentTimeMillis();
        String qFormat = "(addr:\"邹城市\")";
        int totalCount = 0;
        String newQFormat = qFormat + String.format(" AND ad:[%d-01-01 TO %d-12-31]", year, year);
        Pagination pagination1 = JSON.parseObject(this.query(newQFormat, 1), Pagination.class);
        System.out.println("总条数:" + pagination1.getTotal());
        if (pagination1.getTotal() == 0) {
            System.out.println("没有数据:年份:" + year);
            return;
        }
        if (pagination1.getPatents().isEmpty()) {
            System.out.println("没有数据:年份:" + year);
            return;
        }
        int totalPages = this.getPages(pagination1.getTotal(), PAGE_SIZE);
        // 如果总条数大于1000，要按月查询
        if (pagination1.getTotal() > 1000) {
            searchDataByMonth(qFormat, year);
            return;
        } else {
            ergodicPatent(pagination1.getPatents(), year);
        }
        for (int j = 2; j <= totalPages; j++) {
            System.out.println("当前分页数:" + j);
            try {
                Thread.sleep(100);
            } catch (InterruptedException exception) {
                System.out.println(exception);
            }
            Pagination pagination2 = JSON.parseObject(this.query(newQFormat, j), Pagination.class);
            totalCount++;
            if (pagination2.getTotal() == 0) {
                System.out.println("出错了:" + newQFormat);
                break;
            }
            if (pagination2.getPatents().isEmpty()) {
                System.out.println("出错了:" + newQFormat);
                break;
            }
            ergodicPatent(pagination2.getPatents(), year);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("消耗时间" + (endTime - beginTime) / 1000);
        System.out.println("总共发送请求次数" + totalCount);
    }


    /**
     * 从专利汇拉取数据到redis
     */
    @Transactional(rollbackFor = Exception.class)
    public void printData2() {
        long beginTime = System.currentTimeMillis();
        String qFormat = "(addr:\"邹城市\")";
        final int beginYear = 1992;
        int nowYear = Calendar.getInstance().get(Calendar.YEAR);
        int totalCount = 0;
        for (int i = beginYear; i <= nowYear; i++) {
            String newQFormat = qFormat + String.format(" AND ad:[%d-01-01 TO %d-12-31]", i, i);
            Pagination pagination1 = JSON.parseObject(this.query(newQFormat, 1), Pagination.class);
            if (pagination1.getTotal() == 0) {
                System.out.println("没有数据:年份:" + i);
                break;
            }
            if (pagination1.getPatents().isEmpty()) {
                System.out.println("没有数据:年份:" + i);
                break;
            }
            ergodicPatent(pagination1.getPatents(), i);
            int totalPages = this.getPages(pagination1.getTotal(), PAGE_SIZE);

            for (int j = 2; j <= totalPages; j++) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException exception) {
                    System.out.println(exception);
                }
                Pagination pagination2 = JSON.parseObject(this.query(newQFormat, j), Pagination.class);
                totalCount++;
                if (pagination2.getTotal() == 0) {
                    System.out.println("出错了:" + newQFormat);
                    break;
                }
                if (pagination2.getPatents().isEmpty()) {
                    System.out.println("出错了:" + newQFormat);
                    break;
                }
                ergodicPatent(pagination2.getPatents(), i);

            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("消耗时间" + (endTime - beginTime) / 1000);
        System.out.println("总共发送请求次数" + totalCount);
    }


    /**
     * 遍历数据
     *
     * @param list
     */
    private void ergodicPatent(List<PatentPart> list, final int year) {
        if (null == list || list.isEmpty()) {
            return;
        }
        System.out.println("当前总条数据" + list.size());

        list.forEach((x) -> {
            PatentHubDataEntity entity = new PatentHubDataEntity();
            entity.setPublicNumber(x.getId());
            entity.setJsonStr(JSON.toJSONString(x));
            entity.setApplyDate(DateUtil.parse(x.getApplicationDate(), "yyyy-MM-dd"));
            entity.setLegalStatus(x.getLegalStatus());
            entity.setType(x.getType());
            entity.setYear(year);
            patentHubDataService.save(entity);
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

    }

    /**
     * 按月份查询
     *
     * @param qFormat
     * @param year
     */
    private void searchDataByMonth(String qFormat, int year) {
        final int maxMonth = 12;
        int queryCount = 0;
        for (int month = 1; month <= maxMonth; month++) {
            String newQFormat = qFormat + String.format(" AND ad:[%d-%02d-%02d TO %d-%02d-%02d]", year, month, 1, year, month, getDaysByMonth(year, month));
            int nextPage = 1;
            while (nextPage != -1) {
                System.out.println("当前页数" + nextPage);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException exception) {
                    System.out.println(exception);
                }
                Pagination pagination = JSON.parseObject(this.query(newQFormat, nextPage), Pagination.class);
                System.out.println("年份:" + year + "月份:" + month + "条数:" + pagination.getTotal());
                if (pagination.getTotal() == 0) {
                    break;
                }
                if (pagination.getPatents().isEmpty()) {
                    break;
                }
                ergodicPatent(pagination.getPatents(), year);
                nextPage = pagination.getNextPage();
                queryCount++;
            }
        }
        System.out.println("查询次数:" + queryCount);

    }


    /**
     * 从专利汇拉取数据到redis
     */
    public void printData() {
        long beginTime = System.currentTimeMillis();
        String qFormat = "(addr:\"邹城市\")";
        final int maxMonth = 12;
        final int beginYear = 1992;
        int nowYear = Calendar.getInstance().get(Calendar.YEAR);
        int totalCount = 0;
        for (int i = beginYear; i <= nowYear; i++) {
            for (int j = 1; j <= maxMonth; j++) {
                String newQFormat = qFormat + String.format(" AND ad:[%d-%02d-%02d TO %d-%02d-%02d]", i, j, 1, i, j, getDaysByMonth(i, j));
                int nextPage = 1;
                while (nextPage != -1) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException exception) {
                        System.out.println(exception);
                    }
                    Pagination pagination = JSON.parseObject(this.query(newQFormat, nextPage), Pagination.class);
                    totalCount++;

                    if (pagination.getTotal() == 0) {
                        break;
                    }
                    if (pagination.getPatents().isEmpty()) {
                        break;
                    }

                    pagination.getPatents().forEach(x -> {
                        System.out.println(x.getId());
                        System.out.println(JSON.toJSONString(x));
                        redisHashService.set(KEY, x.getId(), JSON.toJSONString(x));
                        // redisListService.lPush(KEY_LIST, x.getId());
                    });

                    nextPage = pagination.getNextPage();

                }


            }

        }
        long endTime = System.currentTimeMillis();
        System.out.println("消耗时间" + (endTime - beginTime) / 1000);
        System.out.println("总共发送请求次数" + totalCount);
    }


    public void updatePatentDetailByMysql() {
        ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
        AtomicInteger ai = new AtomicInteger(0);
        //long size = redisListService.size(PatentHubService.KEY_LIST);
        CustomThreadPoolExecutor exec = new CustomThreadPoolExecutor();
        exec.init();
        ExecutorService pool = exec.getCustomThreadPoolExecutor();
        long size = 11097;
        final int pageSize = 50;
        int pages = getPages(size, pageSize);
        long start = System.currentTimeMillis();
        System.out.println("总页数:" + pages);
        final String transactionsStr = "transactions";
        for (int i = 1; i <= pages; i++) {
            List<PatentHubDataEntity> list = patentHubDataService.pagination(i, pageSize);
            if (null == list || list.isEmpty()) {
                return;
            }
            list.forEach(x -> {
                pool.submit(() -> {
                    if (StrUtil.isNotBlank(x.getJsonStr()) && x.getJsonStr().indexOf(transactionsStr) > 0) {
                        System.out.println(x.getPublicNumber() + "已经更新");
                        return;
                    }
                    String patentStr = this.queryPatent(x.getPublicNumber());
                    if (StrUtil.isBlank(patentStr)) {
                        queue.add(x.getPublicNumber());
                        return;
                    }
                    x.setJsonStr(patentStr);
                    patentHubDataService.updateJson(x);
                    ai.getAndIncrement();
                    System.out.println(x.getPublicNumber() + "更新成功");
                });
            });
        }
        exec.destory();
        long end = System.currentTimeMillis();
        System.out.println(JSON.toJSONString(queue));
        System.out.println("失败条数" + queue.size());
        System.out.println("运行时长:" + (end - start) / 1000);
        System.out.println("条数:" + ai.get());

    }

    /**
     * 插入到redis数据库
     *
     * @param total
     */
    public void insertIntoRedis(int total) {
        final int pageSize = 50;
        int pages = getPages(total, pageSize);
        for (int i = 1; i <= pages; i++) {
            List<PatentHubDataEntity> list = patentHubDataService.pagination(i, pageSize);
            if (null == list || list.isEmpty()) {
                return;
            }
            list.forEach(x -> {
                redisHashService.set(KEY, x.getPublicNumber(), x.getJsonStr());
            });
        }
    }

    /**
     * 更新专利详情
     */
    public void updatePatentDetail() {
        CustomThreadPoolExecutor exec = new CustomThreadPoolExecutor();
        ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();
        AtomicInteger ai = new AtomicInteger(0);
        // 1.初始化
        exec.init();
        ExecutorService pool = exec.getCustomThreadPoolExecutor();
        long size = redisHashService.size(PatentHubService.KEY);
        final int pageSize = 16;
        int pages = getPages(size, pageSize);
        long start = System.currentTimeMillis();

        System.out.println("总页数:" + pages);
        final String transactionsStr = "transactions";
        for (int i = 1; i <= pages; i++) {
            List<String> keys = redisListService.lrange(PatentHubService.KEY_LIST, ((i - 1) * pageSize + 1), (i * pageSize));
            keys.forEach((x) -> {
                pool.execute(() -> {
                    try {
                        ai.getAndIncrement();
                        String existPatentStr = redisHashService.get(PatentHubService.KEY, x);
                        if (StrUtil.isNotBlank(existPatentStr) && existPatentStr.indexOf(transactionsStr) > 0) {
                            System.out.println(x + "已经更新");
                            return;
                        }

                        String patentStr = this.queryPatent(x);
                        if (StrUtil.isBlank(patentStr)) {
                            queue.add(x);
                            return;
                        }
                        redisHashService.set(PatentHubService.KEY, x, patentStr);
                        System.out.println(x + "执行成功");

                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                        queue.add(x);
                        e.printStackTrace();
                    }
                });
            });
            try {
                TimeUnit.MILLISECONDS.sleep(10);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

        }
        exec.destory();
        long end = System.currentTimeMillis();
        System.out.println(JSON.toJSONString(queue));
        System.out.println("失败条数" + queue.size());
        System.out.println("运行时长:" + (end - start) / 1000);
        System.out.println("条数:" + ai.get());
    }

    /**
     * 获取插入sql语句
     *
     * @return
     */
    private String getInsertSql() {
        return " insert into pac_patentinfo " +
                "   (" +
                "   `PlatformID`,`PatNum`,`PatName`,`PatTypeName`,`LawState`,\n" +
                "   `PatAppDate`,`PatApproveDate`,`PublicationDate`,`ExpiryDate`,`AgencyName`,\n" +
                "   `InventPerson`,`ApplyPerson`,`ApplyPersonLast`,`PatAddress`,`PatAddressPrevious`,\n" +
                "   `PatAddressLast`,`PatSubExamDate`,`IPCId`,`EffectReason`,`ApplyPersonType`,\n" +
                "   `DateLast`,`ChinaIPCID`,`ApplyPersonPrevious`,`ApplyPersonTypePrevious`,`IsRollIn`, `CDN`,`PDN`,`PatHubTypeName` \n" +
                "   )" +
                "values(?,?,?,?,?" +
                ",?,?,?,?,?" +
                ",?,?,?,?,?" +
                ",?,?,?,?,?" +
                ",?,?,?,?,?,?,?,?)";
    }

    /**
     * 插入数据到数据库
     *
     * @param platformId
     */
    public void insertIntoDataBase(int platformId) {
        ConcurrentLinkedQueue<PacPatentinfoModel> queue = new ConcurrentLinkedQueue<>();
        CustomThreadPoolExecutor exec = new CustomThreadPoolExecutor();
        exec.init();
        ExecutorService pool = exec.getCustomThreadPoolExecutor();
        long size = redisHashService.size(PatentHubService.KEY);
        final int pageSize = 50;
        int pages = getPages(size, pageSize);
        for (int i = 1; i <= pages; i++) {
            List<String> keys = redisListService.lrange(PatentHubService.KEY_LIST, ((i - 1) * pageSize), (i * pageSize) - 1);
            keys.forEach((key) -> pool.execute(() -> {
                try {
                    Patent patent = JSON.parseObject(redisHashService.get(PatentHubService.KEY, key), Patent.class);
                    PacPatentinfoModel model = transferToModel(patent, platformId);
                    queue.add(model);

                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    System.out.println(key + "失败");
                }

            }));
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
        exec.destory();
        try (Connection conn = dataSource.getConnection(); PreparedStatement pstm = conn.prepareStatement(getInsertSql())) {
            long startTime2 = System.currentTimeMillis();
            conn.setAutoCommit(false);
            while (!queue.isEmpty()) {
                PacPatentinfoModel p = queue.poll();
                if (p == null) {
                    continue;
                }
                pstm.setLong(1, p.getPlatformid());
                pstm.setString(2, p.getAn());
                pstm.setString(3, p.getTi());
                pstm.setInt(4, p.getClazz());
                pstm.setInt(5, p.getLawstate());
                pstm.setString(6, p.getAd());
                pstm.setString(7, p.getApd());
                pstm.setString(8, p.getPd());
                pstm.setString(9, p.getIvd());
                pstm.setString(10, p.getCagc());
                pstm.setString(11, p.getIn1());
                pstm.setString(12, p.getPa1());
                pstm.setString(13, p.getCpa1());
                // 专利地址
                pstm.setString(14, p.getAa());
                // 上一个权利人地址
                pstm.setString(15, p.getPaa());
                // 最后一次专利地址
                pstm.setString(16, p.getCaa());
                pstm.setString(17, p.getSed());
                pstm.setString(18, p.getIc1());
                pstm.setString(19, p.getLsn2());
                pstm.setInt(20, p.getApplyPersonType());
                pstm.setString(21, p.getTfd());
                pstm.setString(22, "");
                pstm.setString(23, p.getPpa1());
                pstm.setInt(24, p.getApplyPersonTypePrevious());
                //pstm.setBoolean(25, p.getIsRollIn());
                pstm.setBoolean(25, StringUtils.isNotBlank(p.getPdn()) && p.getCdn().indexOf("邹城市") != -1);
                pstm.setString(26, p.getCdn());
                pstm.setString(27, p.getPdn());
                pstm.setString(28, p.getPatentTypeName());
                pstm.addBatch();
            }
            pstm.executeBatch();
            conn.commit();
            long entTime2 = System.currentTimeMillis();
            System.out.println("插入数据库花费时间：" + (entTime2 - startTime2) / 1000 + "秒");
            webPlatformService.updatePatentNum(platformId);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());

        }

    }

    /**
     * 更新
     *
     * @param platformId
     */
    public void updateIntoDataBase(int platformId) {

    }

    /**
     * 获取分页的页数
     *
     * @param size
     * @param pageSize
     * @return
     */
    public int getPages(long size, long pageSize) {
        long remValue = size % pageSize;
        long pages;
        if (remValue == 0) {
            pages = size / pageSize;
        } else {
            pages = (int) Math.floor(size / pageSize) + 1;
        }
        return (int) pages;
    }


    /**
     * 将patent转换为 PacPatentinfoModel
     *
     * @param patent
     * @return
     */
    public PacPatentinfoModel transferToModel(Patent patent, int platformId) {
        PacPatentinfoModel model = new PacPatentinfoModel();
        List<String> inValidList = PatentHubTransferUtil.getInValid(patent);
        model.setPlatformid(platformId);
        //申请号
        model.setAn(patent.getApplicationNumber());
        //专利名称
        model.setTi(patent.getTitle());
        // 专利类型
        model.setClazz(PatentTypeEnum.getType(patent.getType()));
        model.setPatentTypeName(patent.getType());
        // 法律状态
        model.setLsnt(patent.getLegalStatus());
        // 专利申请日
        model.setAd(patent.getApplicationDate());
        // 授权日
        model.setApd(PatentHubTransferUtil.getApd(patent));
        //公开日 只有发明专利才有公开日
        model.setPd(PatentHubTransferUtil.getPd(patent));
        if (inValidList != null && inValidList.size() > 0) {
            // 专利失效日
            model.setIvd(inValidList.get(0));
            // 失效原因
            model.setLsn2(inValidList.get(1));
        }
        // 代理机构
        model.setCagc(patent.getAgency());
        // 发明人
        model.setIn1(patent.getInventor());
        // 当前权利人
        model.setPa1(patent.getAssignee());
        // 变更后，最后一次专利申请人(权利人)
        model.setCpa1(patent.getAssignee());
        // 实审日期
        model.setSed(PatentHubTransferUtil.getSed(patent));
        // IPC分类
        model.setIc1(patent.getMainIpc());
        // 专利地址  aa caa cdn 应该是一样的
        model.setAa(patent.getApplicantAddress());
        // 变更后，最后一次专利地址---当前权利人地址
        model.setCaa(patent.getApplicantAddress());
        // 当前地址
        model.setCdn(patent.getApplicantAddress());

        PatentChangeInfo changeInfo = PatentHubTransferUtil.getPatentChangeInfo(patent);

        if (null != changeInfo) {
            // 变更前第一专利申请/权利人
            model.setPpa1(changeInfo.getPpa1());
            // 专利地址----权利人地址---上一个权利人地址
            model.setPaa(changeInfo.getPaa());
            // 转移日期
            model.setTfd(changeInfo.getTfd());
            // 转移前地址
            model.setPdn(changeInfo.getPaa());
            // 专利转移的地址和原先不匹配
            if (!model.getPa1().equals(changeInfo.getPa1())) {
                // 当前权利人
                if (StrUtil.isNotBlank(changeInfo.getPa1())) {
                    //model.setPa1(changeInfo.getPa1());
                }
                // 变更后，最后一次专利申请人(权利人)
                if (StrUtil.isNotBlank(changeInfo.getPa1())) {
                    model.setCpa1(changeInfo.getPa1());
                }

                if (StrUtil.isNotBlank(changeInfo.getAa())) {
                    // 专利地址  aa caa cdn 应该是一样的
                    //model.setAa(changeInfo.getAa());
                    // 变更后，最后一次专利地址---当前权利人地址
                    //model.setCaa(changeInfo.getAa());
                    // 当前地址
                    //model.setCdn(changeInfo.getAa());
                }
            }
            List<String> addressChangeInfo = PatentHubTransferUtil.getAddressChangeInfo(patent);
            if (addressChangeInfo != null) {
                System.out.println(patent.getId() + ":" + JSON.toJSONString(addressChangeInfo));
            }

        }


        return model;

    }


    /**
     * 专利汇 获取数据
     *
     * @param q
     * @param nextPage
     * @return
     */
    public String query(String q, int nextPage) {
        String baseUrl = "https://www.patenthub.cn/api/s";
        // String q = "(addr:\"江苏省常州市武进区\") AND ad:[2017-01-01 TO 2017-01-31]";
        int version = 1;
        Map<String, Object> paramMap = new HashMap<>(7);
        paramMap.put("ds", "cn");
        paramMap.put("t", TOKEN);
        paramMap.put("q", q);
        paramMap.put("v", version);
        paramMap.put("hl", "0");
        paramMap.put("p", nextPage);
        paramMap.put("ps", PAGE_SIZE);

        return HttpUtils.get(baseUrl, paramMap);
    }

    /**
     * 专利汇-获取专利详细信息
     *
     * @param patentId
     * @return
     */
    public String queryPatent(String patentId) {
        String baseUrl = "https://www.patenthub.cn/api/patent/base";
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("v", 1);
        paramMap.put("t", TOKEN);
        paramMap.put("id", patentId);
        String str = HttpUtil.get(baseUrl, paramMap);
        if (StrUtil.isBlank(str)) {
            return null;
        }
        PatentResponse patentResponse = JSON.parseObject(str, PatentResponse.class);
        if (!patentResponse.isSuccess()) {
            return null;
        }
        if (patentResponse == null) {
            return null;
        }
        String lawStatusStr = this.queryLawStatus(patentId);
        TransactionModel transactionModel = JSON.parseObject(lawStatusStr, TransactionModel.class);
        if (transactionModel.isSuccess() && transactionModel.getTransactions() != null && !transactionModel.getTransactions().isEmpty()) {
            patentResponse.getPatent().setTransactions(transactionModel.getTransactions());
        } else {
            System.out.println(patentId + " 没有法律状态");
        }
        return JSON.toJSONString(patentResponse.getPatent());
    }

    /**
     * 查询法律信息
     *
     * @param patentId
     * @return
     */
    private String queryLawStatus(String patentId) {
        String baseUrl = "https://www.patenthub.cn/api/patent/tx";
        Map<String, Object> paramMap = new HashMap<>(3);
        paramMap.put("v", 1);
        paramMap.put("t", TOKEN);
        paramMap.put("id", patentId);
        return HttpUtil.get(baseUrl, paramMap);

    }

    public void updatePatent() {
        //redisHashService
    }


    public int getDaysByMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.clear();
        c.set(Calendar.YEAR, year);
        //设置月份，因为月份从0开始，所以用month - 1
        c.set(Calendar.MONTH, month - 1);
        int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        return lastDay;
    }


    public void queryRedisPatent() {
        long size = redisHashService.size(PatentHubService.KEY);
        final int pageSize = 1000;
        int pages = this.getPages(size, pageSize);
        Set<String> lawState = new HashSet<>();
        for (int i = 1; i <= pages; i++) {
            List<String> keys = redisListService.lrange(PatentHubService.KEY_LIST, ((i - 1) * pageSize + 1), (i * pageSize));

            keys.forEach((x) -> {
                String patentStr = redisHashService.get(KEY, x);
                Patent patent = JSON.parseObject(patentStr, Patent.class);
                if (patent != null) {
                    lawState.add(patent.getLegalStatus());
                }
            });

        }
        System.out.println(JSON.toJSONString(lawState));
    }


    public static void main(String[] args) {
        // new PatentHubService().printData();
        // System.out.println(new PatentHubService().query("asdfafafadfaf", 1));
        // System.out.println(new PatentHubService().queryLawStatus("CN108251808A"));
        new PatentHubService().printData();
    }
}
